const app = getApp()

Page({
  data: {
    userInfo: null,
    canIUseGetUserProfile: false,
    isAgree: false
  },

  onLoad() {
    // 直接用Storage判断
    console.log('login???')
    const isLogin = wx.getStorageSync('isLogin');
    console.log('login', isLogin)
    if (isLogin) {
      console.log('isLogin')
      wx.switchTab({
        url: '/pages/index/index'
      });
      return;
    }
    console.log('notLogin')
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },

  handleLogin() {
    if (!this.data.isAgree) {
      wx.showToast({
        title: '请先同意用户协议和隐私政策',
        icon: 'none'
      })
      return
    }

    wx.getUserProfile({
      desc: '用于完善用户资料',
      success: (res) => {
        this.setData({
          userInfo: res.userInfo
        })
        // 保存用户信息到全局
        app.globalData.userInfo = res.userInfo
        // 保存到本地存储
        wx.setStorageSync('userInfo', res.userInfo)
        wx.setStorageSync('isLogin', true)
        // 登录成功后跳转到首页
        wx.switchTab({
          url: '/pages/index/index',
          success: () => {
            wx.showToast({
              title: '登录成功',
              icon: 'success'
            })
          }
        })
      },
      fail: (err) => {
        console.log('获取用户信息失败', err)
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    })
  },

  handleAgreementChange(e) {
    this.setData({
      isAgree: e.detail.value.length > 0
    })
  },

  showAgreement() {
    wx.navigateTo({
      url: '/pages/agreement/agreement'
    })
  },

  showPrivacy() {
    wx.navigateTo({
      url: '/pages/privacy/privacy'
    })
  }
}) 